<?php
/**
 *
 *
 * This file is part of Webappkit, a packages system for PHP web apps
 * @link http://webappkit.net
 * @package
 * @subpackage
 * @author J.Ducastel <nospam0@ducastel.name>
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 */

/**
 * @property array $choices label => value
 */
class DjChoiceField extends DjField {

    /**
     * return the cleaned value
     * if value does not validate, raise a DjValidationError
     * @param mixed $input
     * @return mixed
     */
    public function clean($input) {
        $this->_cleanRequired($input);
        $input = $this->_normalize($input);
        if (!in_array($input, $this->choices))
            throw new DjValidationError($this->error_messages['invalid_choice']);
        return $input;
    }

    /**
     * default widget is <select>
     */
    protected function _widget_autoValue() {
        return new DjSelect();
    }

    protected $error_messages = array(
        'required' => 'This field is required'
        , 'invalid_choice' => 'This is not a valid choice'
    );

    protected $choices = array();
    protected function _choices_check($x) {
        return is_array($x);
    }
    protected function _choices_inputFilter($x) {
        // transfering choices to widget
        $this->widget->choices = $x;
        return $x;
    }

    /**
     * normalize input value
     * @param mixed $value
     * @return mixed
     */
    protected function _normalize($value) {
        return $value;
    }
}